package router

import (
	"broker/interface/iserver"
	"broker/struct/datapack"
	"broker/struct/model"
	"broker/utils/logger"
)

/**
 * @Description
 * @Author huan.wang
 * @Date 2021/4/26 9:34 下午
 **/

type SubScribeRouter struct {
}

func NewSubScribeRouter() *SubScribeRouter {
	return &SubScribeRouter{}
}

func (s SubScribeRouter) PreHandle(request iserver.IRequest) interface{} {
	sdp := datapack.NewSubscribeDataPack()
	subMsg, err := sdp.UnPack(request.GetData())
	if err != nil {
		logger.Error.Println("[Subscribe] subscribe message datapack err", err)
		return nil
	}
	return subMsg
}

func (s SubScribeRouter) Handle(request iserver.IRequest, param interface{}) interface{} {
	subMsg := param.(*model.SubscribeMessage)
	subscriber := model.NewSubscriber(request.GetConnection().GetConnID(), subMsg.TopicFilters)
	err := request.GetConnection().GetTcpServer().GetTopicManager().Subscribe(subscriber)
	if err != nil {
		logger.Error.Println("[Subscribe] add subscriber err ", err)
		return nil
	}
	return subMsg
}

func (s SubScribeRouter) PostHandle(request iserver.IRequest, param interface{}) {
	subMsg := param.(*model.SubscribeMessage)
	//发送suback消息
	sadp := datapack.NewSubscribeAckDataPack()
	subAckMsg := model.NewSubAckMessage()
	subAckMsg.PacketID = subMsg.PacketID
	subAckMsg.ReturnCode = 0x00
	msgData, err := sadp.Pack(subAckMsg)
	if err != nil {
		logger.Error.Println("[SubscribeACK] sub ack datapack err ", err)
	}
	subAckMsg.SetData(msgData)
	go request.GetConnection().SendMsg(subAckMsg)
}
